package com.tanhua.server.service;


import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.vo.ErrorResult;
import com.tanhua.domain.vo.UserInfoVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.server.utils.GetAgeUtil;
import com.tanhua.server.utils.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class UserInfoService {

    //    订阅UserInfoApi接口
    @Reference
    private UserInfoApi userInfoApi;
    //    注入redisTemplate对象
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    //     注入ossTemplate对象
    @Autowired
    private OssTemplate ossTemplate;
    //    注入ThreaLocalUtils对象
    @Autowired
    private ThreadLocalUtils threadLocalUtils;
    //创建一个客户端
    @Autowired
    private FastFileStorageClient fastFileStorageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;

    /**
     * 延长用户的token令牌时间
     */
    public User extensionOfTimeByToken(String token) {
//      将Token拼接
        String prefix = "TOKEN_" + token;
//      将拼接后的token作为key 到redis中查找是否这个值
        String userString = redisTemplate.opsForValue().get(prefix);
//        如果不存在 那么就报异常
        if (StringUtils.isEmpty(userString)) {
            throw new TanHuaException(ErrorResult.loginInvalid());
        }
//        如果存在 将此token令牌的时间设置为1天
        redisTemplate.expire(prefix, 1, TimeUnit.DAYS);
//        解析redis中获取到的值 转换为一个user对象
        return JSON.parseObject(userString, User.class);
    }

    /**
     * 读取用户信息
     *
     * @param userID
     * @param huanxinID
     * @param
     * @return
     */
    public UserInfoVo readUsersInfo(String userID, String huanxinID) {
//       创建一个userInfo对象 用于接受数据库返回的结果
        UserInfo userInfo = new UserInfo();
        Long userId = threadLocalUtils.getUserId();
        if (userID != null) {
            userInfo = userInfoApi.findUserInfoByID(Long.parseLong(userID));
        } else if (huanxinID != null) {
            userInfo = userInfoApi.findUserInfoByID(Long.parseLong(huanxinID));
        } else if (userId != null) {
//            调用方法 传入id值
            userInfo = userInfoApi.findUserInfoByID(userId);
        } else {
            log.debug("没有传入任何的参数");
            throw new TanHuaException(ErrorResult.error());
        }

//        创建一个前端接受的对象 UserInfoVo
        UserInfoVo userInfoVo = new UserInfoVo();
//        复制数据库对象属性到前端对象属性
        BeanUtils.copyProperties(userInfo, userInfoVo);
//        age属性类型封装不上  需要单独设置
        if (userInfo.getAge() == null) {
            log.debug("数据库查询到对象没有age属性值");
            int age = GetAgeUtil.getAge(userInfo.getBirthday());
            userInfo.setAge(age);
        }
        userInfoVo.setAge(userInfo.getAge() + "");
        log.debug("返回前端的vo对象；" + userInfoVo);
        return userInfoVo;
    }

    /**
     * 修改用户信息
     */
    public void editUsersInfo(UserInfoVo userInfoVo) {
        User user = threadLocalUtils.getUser();

//        创建一个userInfo对象 将UserInfoVo对象的属性复制到userInfo属性上
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoVo, userInfo);
//        如果userInfoVo的生日属性存在 那么就同步更新它的age属性
        if (!StringUtils.isEmpty(userInfo.getBirthday())) {
            //获得生日信息
            String birthday = userInfo.getBirthday();
            //计算出相应的年龄
            int age = GetAgeUtil.getAge(birthday);
            //修改age
            userInfo.setAge(age);
        }
//        设置userinfo的id
        userInfo.setId(user.getId());
//        调用方法 传入对象
        userInfoApi.updateInfo(userInfo);
    }

    /**
     * 修改头像
     */
    public void editUserHeader(MultipartFile headPhoto) {
        try {
            //获得对象用户
            User user = threadLocalUtils.getUser();
//      上传图片到oss服务器
//            String fileAddress = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
            //调用公共方法 获得fdfs文件访问地址
            String PicUrl = getUploadUrlByFdfs(headPhoto);
            //将图片地址设置到userInfo对象
            UserInfo userInfo = new UserInfo();
            userInfo.setId(user.getId());
            userInfo.setAvatar(PicUrl);
//      调用UserinfoApi
            log.debug("即将更新图片的对象：" + userInfo);
            userInfoApi.updateInfo(userInfo);

        } catch (IOException e) {
            throw new TanHuaException(ErrorResult.picUploadFailed());
        }


    }

     String getUploadUrlByFdfs(MultipartFile headPhoto) throws IOException {
        //获得视频文件的后缀名
        String headPhotoOriginalFilename = headPhoto.getOriginalFilename();
        String suffix = headPhotoOriginalFilename.substring(headPhotoOriginalFilename.lastIndexOf(".") + 1);
        //调用fastFileStorageClient方法
        StorePath storePath = fastFileStorageClient.uploadFile(headPhoto.getInputStream(), headPhoto.getSize(), suffix, null);
        //获取文件的路径
        String fullPath = storePath.getFullPath();
        //使用fdfsWebServer获得storage的部署路径 然后拼接storage的文件名路径
        return fdfsWebServer.getWebServerUrl() + fullPath;
    }
}
